package com.ruoyi.wechat.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.model.WeChatUserInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.app.service.AppLoginService;
import com.ruoyi.wechat.config.WxMaConfiguration;
import com.ruoyi.wechat.config.WxMaProperties;
import com.ruoyi.wechat.service.WechatMiniappService;
import com.ruoyi.wechat.vo.WeChatMiniappLoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * description: 微信小程序接口实现类
 * date: 2023年03月22日 11:27
 * author: tmac-1
 * version: 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class WechatMiniappServiceImpl implements WechatMiniappService {
    private final WxMaProperties wxMaProperties;
    private final AppLoginService appLoginService;

    @Override
    public String login(WeChatMiniappLoginVo weChatMiniappLoginVo) {
        log.info("登录参数：" + JSON.toJSONString(weChatMiniappLoginVo));
        String appid = wxMaProperties.getConfigs().get(0).getAppid();
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        try {
            // code换取session
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(weChatMiniappLoginVo.getCode());
            log.info("code换取session：{}", session);
            if (!wxService.getUserService().checkUserInfo(session.getSessionKey(), weChatMiniappLoginVo.getRawData(), weChatMiniappLoginVo.getSignature())) {
                throw new ServiceException("用户信息校验失败");
            }
            // 解密用户信息
            // WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(session.getSessionKey(), weChatMiniappLoginVo.getEncryptedData(), weChatMiniappLoginVo.getIv());
            //g.info("解密用户信息：{}", userInfo);
            // 获取用户绑定手机号信息
            WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(session.getSessionKey(), weChatMiniappLoginVo.getEncryptedData(), weChatMiniappLoginVo.getIv());
            log.info("获取用户绑定手机号信息：{}", phoneNoInfo);
            WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
            weChatUserInfo.setUserName(phoneNoInfo.getPhoneNumber());
            weChatUserInfo.setNickName(weChatMiniappLoginVo.getNickName());
            weChatUserInfo.setAvatar(weChatMiniappLoginVo.getAvatarUrl());
            weChatUserInfo.setSex(weChatMiniappLoginVo.getGender());
            weChatUserInfo.setMobile(phoneNoInfo.getPhoneNumber());
            weChatUserInfo.setOpenid(session.getOpenid());
            weChatUserInfo.setUnionid(session.getUnionid());
            return appLoginService.getToken(weChatUserInfo);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(e.getError().getErrorMsg());
        }
    }
}
